<template>
  <div class="data-configuration">
    <!-- 数据项标题 -->
    <div class="section-header">
      <h2 class="section-title">数据项配置</h2>
      <p class="section-description">管理产品、设备、工艺和人员等基础数据</p>
    </div>

    <!-- 数据统计 -->
    <div class="statistics-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card stat-card-product" @click="scrollToSection('product')">
            <div class="stat-icon">
              <el-icon :size="40">
                <Box />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ productData.length }}</div>
              <div class="stat-label">产品总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-equipment" @click="scrollToSection('equipment')">
            <div class="stat-icon">
              <el-icon :size="40">
                <Setting />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ equipmentData.length }}</div>
              <div class="stat-label">设备总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-process" @click="scrollToSection('process')">
            <div class="stat-icon">
              <el-icon :size="40">
                <Operation />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ processData.length }}</div>
              <div class="stat-label">工序总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-personnel" @click="scrollToSection('personnel')">
            <div class="stat-icon">
              <el-icon :size="40">
                <User />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ personnelData.length }}</div>
              <div class="stat-label">人员总数</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 产品数据 -->
    <div ref="productSection" class="aps-section">
      <el-row>
        <span style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          ">
          产品数据
        </span>
        <div style="float: right">
          <el-button type="text" @click="toggleProductData">
            {{ showProductData ? "收起" : "展开" }}
          </el-button>
        </div>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showProductData" style="margin-top: 20px">
          <!-- 搜索组件 -->
          <ProductSearchComponent :loading="productLoading" @search="handleProductSearch" @reset="handleProductReset" />

          <!-- 产品数据表格 -->
          <IdooAddRowTable ref="productTableRef" :data="productData" :columns="productColumns" :loading="productLoading"
            style="width: 100%; min-height: 300px" @row-save="handleProductSave" @row-delete="handleProductDelete" />
        </div>
      </transition>
    </div>

    <!-- 仪器设备数据 -->
    <div ref="equipmentSection" class="aps-section">
      <el-row>
        <span style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          ">
          仪器设备数据
        </span>
        <div style="float: right">
          <el-button type="text" @click="toggleEquipmentData">
            {{ showEquipmentData ? "收起" : "展开" }}
          </el-button>
        </div>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showEquipmentData" style="margin-top: 20px">
          <!-- 搜索组件 -->
          <EquipmentSearchComponent :loading="equipmentLoading" @search="handleEquipmentSearch"
            @reset="handleEquipmentReset" />

          <!-- 设备数据表格 -->
          <IdooAddRowTable ref="equipmentTableRef" :data="equipmentData" :columns="equipmentColumns"
            :loading="equipmentLoading" style="width: 100%; min-height: 300px" @row-save="handleEquipmentSave"
            @row-delete="handleEquipmentDelete" />
        </div>
      </transition>
    </div>

    <!-- 工艺/工序数据 -->
    <div ref="processSection" class="aps-section">
      <el-row>
        <span style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          ">
          工艺/工序数据
        </span>
        <div style="float: right">
          <el-button type="text" @click="toggleProcessData">
            {{ showProcessData ? "收起" : "展开" }}
          </el-button>
        </div>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showProcessData" style="margin-top: 20px">
          <!-- 工艺-工序管理组件 -->
          <CraftOperationManager />
        </div>
      </transition>
    </div>

    <!-- 人员数据 -->
    <div ref="personnelSection" class="aps-section">
      <el-row>
        <span style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          ">
          人员数据
        </span>
        <div style="float: right">
          <el-button type="text" @click="togglePersonnelData">
            {{ showPersonnelData ? "收起" : "展开" }}
          </el-button>
        </div>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showPersonnelData" style="margin-top: 20px">
          <!-- 搜索组件 -->
          <!-- <PersonnelSearchComponent
            :loading="personnelLoading"
            @search="handlePersonnelSearch"
            @reset="handlePersonnelReset"
          /> -->

          <!-- 人员数据表格 -->
          <IdooAddRowTable ref="personnelTableRef" :data="personnelData" :columns="personnelColumns"
            :loading="personnelLoading" style="width: 100%; min-height: 300px" @row-save="handlePersonnelSave"
            @row-delete="handlePersonnelDelete" />
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Box, Setting, Operation, User } from "@element-plus/icons-vue";
import IdooAddRowTable from "@/idoo-core/table/add-row-table/IdooAddRowTable.vue";
import { CellType } from "@/idoo-core/table/add-row-table/IdooAddRowTable";
import ProductSearchComponent from "@/components/common/ProductSearchComponent.vue";
import EquipmentSearchComponent from "@/components/common/EquipmentSearchComponent.vue";
import CraftOperationManager from "@/components/configuration/CraftOperationManager.vue";
// import ProcessSearchComponent from '@/components/common/ProcessSearchComponent.vue'
// import PersonnelSearchComponent from '@/components/common/PersonnelSearchComponent.vue'
import { basicProductApi } from "@/api/basicProduct";
import { basicEquipApi } from "@/api/basicEquip";

export default {
  name: "DataConfiguration",
  components: {
    Box,
    Setting,
    Operation,
    User,
    IdooAddRowTable,
    ProductSearchComponent,
    EquipmentSearchComponent,
    CraftOperationManager,
    // ProcessSearchComponent,
    // PersonnelSearchComponent
  },
  setup() {
    // 显示控制
    const showProductData = ref(true);
    const showEquipmentData = ref(true);
    const showProcessData = ref(true);
    const showPersonnelData = ref(true);

    // 表格引用
    const productTableRef = ref();
    const equipmentTableRef = ref();
    const processTableRef = ref();
    const personnelTableRef = ref();

    // 区块引用
    const productSection = ref();
    const equipmentSection = ref();
    const processSection = ref();
    const personnelSection = ref();

    // 产品数据相关状态
    const productLoading = ref(false);
    const productSearchParams = ref({});

    // 设备数据相关状态
    const equipmentLoading = ref(false);
    const equipmentSearchParams = ref({});

    // 工序数据相关状态
    const processLoading = ref(false);
    const processSearchParams = ref({});

    // 人员数据相关状态
    const personnelLoading = ref(false);
    const personnelSearchParams = ref({});

    // 产品数据表格列配置
    const productColumns = [
      {
        prop: "productCode",
        label: "产品编号",
        type: CellType.INPUT,
        width: 400,
        required: true,
        placeholder: "请输入产品编号",
      },
      {
        prop: "productName",
        label: "产品名称",
        type: CellType.INPUT,
        width: 400,
        required: true,
        placeholder: "请输入产品名称",
      },
      {
        prop: "productType",
        label: "产品类别",
        type: CellType.INPUT,
        width: 400,
        required: true,
        placeholder: "请输入产品类别",
      },
    ];

    // 设备数据表格列配置
    const equipmentColumns = [
      {
        prop: "equipCode",
        label: "设备编号",
        type: CellType.INPUT,
        width: 300,
        required: true,
        placeholder: "请输入设备编号",
      },
      {
        prop: "equipName",
        label: "设备名称",
        type: CellType.INPUT,
        width: 300,
        required: true,
        placeholder: "请输入设备名称",
      },
      {
        prop: "equipType",
        label: "设备类型",
        type: CellType.INPUT,
        width: 200,
        required: true,
        placeholder: "请输入设备类型",
      },
      {
        prop: "equipEfficiency",
        label: "效率系数",
        type: CellType.INPUT_NUMBER,
        width: 200,
        required: true,
        min: 0,
        precision: 2,
        placeholder: "请输入产能",
      },
      {
        prop: "equipCapacity",
        label: "理论产能(件/分)",
        type: CellType.INPUT_NUMBER,
        width: 200,
        required: true,
        min: 0,
        placeholder: "请输入产能",
      },
      {
        prop: "equipStatus",
        label: "状态",
        type: CellType.SELECT,
        width: 200,
        required: true,
        placeholder: "请选择状态",
        options: [
          { label: "运行中", value: "运行中" },
          { label: "维护中", value: "维护中" },
          { label: "故障", value: "故障" },
          { label: "停机", value: "停机" },
        ],
      },
    ];

    // 工序数据表格列配置
    const processColumns = [
      {
        prop: "processId",
        label: "工序编号",
        type: CellType.INPUT,
        width: 150,
        required: true,
        placeholder: "请输入工序编号",
      },
      {
        prop: "processName",
        label: "工序名称",
        type: CellType.INPUT,
        width: 200,
        required: true,
        placeholder: "请输入工序名称",
      },
      {
        prop: "sequence",
        label: "工序顺序",
        type: CellType.INPUT_NUMBER,
        width: 100,
        required: true,
        min: 1,
        placeholder: "请输入工序顺序",
      },
      {
        prop: "duration",
        label: "标准工时(分钟/件)",
        type: CellType.INPUT_NUMBER,
        width: 130,
        required: true,
        min: 0,
        placeholder: "请输入标准时长",
      },
      {
        prop: "skillLevel",
        label: "技能要求",
        type: CellType.SELECT,
        width: 120,
        required: true,
        placeholder: "请选择技能要求",
        options: [
          { label: "初级", value: "初级" },
          { label: "中级", value: "中级" },
          { label: "高级", value: "高级" },
        ],
      },
      {
        prop: "equipStatus",
        label: "状态",
        type: CellType.SELECT,
        width: 100,
        required: true,
        placeholder: "请选择状态",
        options: [
          { label: "启用", value: "启用" },
          { label: "停用", value: "停用" },
        ],
      },
    ];

    // 人员数据表格列配置
    const personnelColumns = [
      {
        prop: "employeeId",
        label: "员工编号",
        type: CellType.INPUT,
        width: 120,
        required: true,
        placeholder: "请输入员工编号",
      },
      {
        prop: "employeeName",
        label: "员工姓名",
        type: CellType.INPUT,
        width: 150,
        required: true,
        placeholder: "请输入员工姓名",
      },
      {
        prop: "department",
        label: "所属部门",
        type: CellType.INPUT,
        width: 150,
        required: true,
        placeholder: "请输入所属部门",
      },
      {
        prop: "position",
        label: "职位",
        type: CellType.INPUT,
        width: 120,
        required: true,
        placeholder: "请输入职位",
      },
      {
        prop: "skillLevel",
        label: "技能等级",
        type: CellType.SELECT,
        width: 120,
        required: true,
        placeholder: "请选择技能等级",
        options: [
          { label: "初级", value: "初级" },
          { label: "中级", value: "中级" },
          { label: "高级", value: "高级" },
        ],
      },
      {
        prop: "equipStatus",
        label: "状态",
        type: CellType.SELECT,
        width: 100,
        required: true,
        placeholder: "请选择状态",
        options: [
          { label: "在岗", value: "在岗" },
          { label: "休假", value: "休假" },
          { label: "离职", value: "离职" },
          { label: "培训", value: "培训" },
        ],
      },
    ];

    // 产品数据
    const productData = reactive([]);

    // 设备数据
    const equipmentData = reactive([]);

    // 工序数据（保留原有数据结构，但不再使用）
    const processData = reactive([
      {
        id: 1,
        processId: "PR001",
        processName: "原料准备",
        sequence: 1,
        duration: 30,
        skillLevel: "初级",
        equipStatus: "启用",
      },
      {
        id: 2,
        processId: "PR002",
        processName: "机械加工",
        sequence: 2,
        duration: 120,
        skillLevel: "高级",
        equipStatus: "启用",
      },
      {
        id: 3,
        processId: "PR003",
        processName: "质量检测",
        sequence: 3,
        duration: 45,
        skillLevel: "中级",
        equipStatus: "启用",
      },
    ]);

    // 人员数据
    const personnelData = reactive([
      {
        id: 1,
        employeeId: "EMP001",
        employeeName: "张三",
        department: "生产部",
        position: "机械操作员",
        skillLevel: "高级",
        equipStatus: "在岗",
      },
      {
        id: 2,
        employeeId: "EMP002",
        employeeName: "李四",
        department: "质检部",
        position: "质检员",
        skillLevel: "中级",
        equipStatus: "在岗",
      },
      {
        id: 3,
        employeeId: "EMP003",
        employeeName: "王五",
        department: "生产部",
        position: "装配工",
        skillLevel: "初级",
        equipStatus: "休假",
      },
    ]);

    // 产品数据相关方法
    const loadProductData = async (params = {}) => {
      try {
        productLoading.value = true;
        const searchParams = {
          ...productSearchParams.value,
          ...params,
        };
        const response =
          await basicProductApi.getProductsByCurrentTenant(searchParams);

        if (response && response.data) {
          // 后端返回的data直接是数组，不是分页格式
          productData.splice(0, productData.length, ...response.data);
        }
      } catch (error) {
        console.error("加载产品数据失败:", error);
        ElMessage.error("加载产品数据失败: " + (error.message || "未知错误"));
      } finally {
        productLoading.value = false;
      }
    };

    const handleProductSearch = (searchParams) => {
      productSearchParams.value = searchParams;
      loadProductData();
    };

    const handleProductReset = () => {
      productSearchParams.value = {};
      loadProductData();
    };

    const handleProductSave = async (rowData, index, callback) => {
      try {
        productLoading.value = true;

        if (rowData.isNew) {
          // 新增产品
          const response = await basicProductApi.createProduct(rowData);
          if (response && response.success) {
            ElMessage.success("产品创建成功");
            loadProductData();
            // 通知表格组件保存成功
            callback && callback({ success: true });
          } else {
            console.log(response);
            ElMessage.error(response?.message || "产品创建失败");
            // 通知表格组件保存失败
            callback && callback({ success: false });
          }
        } else {
          // 更新产品
          const response = await basicProductApi.updateProduct(
            rowData.id,
            rowData,
          );
          if (response && response.success) {
            ElMessage.success("产品更新成功");
            loadProductData();
            // 通知表格组件保存成功
            callback && callback({ success: true });
          } else {
            ElMessage.error(response?.message || "产品更新失败");
            // 通知表格组件保存失败
            callback && callback({ success: false });
          }
        }
      } catch (error) {
        console.error("保存产品失败:", error);
        ElMessage.error("保存产品失败: " + (error.message || "未知错误"));
        // 通知表格组件保存失败
        callback && callback({ success: false });
      } finally {
        productLoading.value = false;
      }
    };

    const handleProductDelete = async (rowData) => {
      try {
        productLoading.value = true;
        const response = await basicProductApi.deleteProduct(rowData.id);

        if (response && response.success) {
          ElMessage.success("产品删除成功");
          loadProductData();
        } else {
          ElMessage.error(response?.message || "产品删除失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除产品失败:", error);
          ElMessage.error("删除产品失败: " + (error.message || "未知错误"));
        }
      } finally {
        productLoading.value = false;
      }
    };

    // 设备数据相关方法
    const loadEquipmentData = async (params = {}) => {
      try {
        equipmentLoading.value = true;
        const searchParams = {
          ...equipmentSearchParams.value,
          ...params,
        };
        const response =
          await basicEquipApi.getEquipsByCurrentTenant(searchParams);

        if (response && response.data) {
          // 后端返回的data直接是数组，不是分页格式
          equipmentData.splice(0, equipmentData.length, ...response.data);
        }
      } catch (error) {
        console.error("加载设备数据失败:", error);
        ElMessage.error("加载设备数据失败: " + (error.message || "未知错误"));
      } finally {
        equipmentLoading.value = false;
      }
    };

    const handleEquipmentSearch = (searchParams) => {
      equipmentSearchParams.value = searchParams;
      loadEquipmentData();
    };

    const handleEquipmentReset = () => {
      equipmentSearchParams.value = {};
      loadEquipmentData();
    };

    const handleEquipmentSave = async (rowData, index, callback) => {
      try {
        equipmentLoading.value = true;

        if (rowData.isNew) {
          // 新增设备
          const response = await basicEquipApi.createEquip(rowData);
          if (response && response.success) {
            ElMessage.success("设备创建成功");
            loadEquipmentData();
            // 通知表格组件保存成功
            callback && callback({ success: true });
          } else {
            console.log(response);
            ElMessage.error(response?.message || "设备创建失败");
            // 通知表格组件保存失败
            callback && callback({ success: false });
          }
        } else {
          // 更新设备
          const response = await basicEquipApi.updateEquip(rowData.id, rowData);
          if (response && response.success) {
            ElMessage.success("设备更新成功");
            loadEquipmentData();
            // 通知表格组件保存成功
            callback && callback({ success: true });
          } else {
            ElMessage.error(response?.message || "设备更新失败");
            // 通知表格组件保存失败
            callback && callback({ success: false });
          }
        }
      } catch (error) {
        console.error("保存设备失败:", error);
        ElMessage.error("保存设备失败: " + (error.message || "未知错误"));
        // 通知表格组件保存失败
        callback && callback({ success: false });
      } finally {
        equipmentLoading.value = false;
      }
    };

    const handleEquipmentDelete = async (rowData) => {
      try {
        equipmentLoading.value = true;
        const response = await basicEquipApi.deleteEquip(rowData.id);

        if (response && response.success) {
          ElMessage.success("设备删除成功");
          loadEquipmentData();
        } else {
          ElMessage.error(response?.message || "设备删除失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除设备失败:", error);
          ElMessage.error("删除设备失败: " + (error.message || "未知错误"));
        }
      } finally {
        equipmentLoading.value = false;
      }
    };

    // 工序数据相关方法
    const loadProcessData = async (params = {}) => {
      try {
        processLoading.value = true;
        // 模拟API调用，实际项目中需要替换为真实的API
        // 无需分页，直接显示所有数据
      } catch (error) {
        console.error("加载工序数据失败:", error);
        ElMessage.error("加载工序数据失败: " + (error.message || "未知错误"));
      } finally {
        processLoading.value = false;
      }
    };

    const handleProcessSearch = (searchParams) => {
      processSearchParams.value = searchParams;
      loadProcessData();
    };

    const handleProcessReset = () => {
      processSearchParams.value = {};
      loadProcessData();
    };

    const handleProcessSave = async (rowData, index, callback) => {
      try {
        processLoading.value = true;

        if (rowData.isNew) {
          console.log("新增工序", rowData);
          // 模拟新增工序API调用
          const newProcess = {
            ...rowData,
            id: Date.now(), // 模拟ID生成
          };
          processData.push(newProcess);
          ElMessage.success("工序创建成功");
          // 通知表格组件保存成功
          callback && callback({ success: true });
        } else {
          console.log("更新工序", rowData);
          // 模拟更新工序API调用
          const processIndex = processData.findIndex(
            (item) => item.id === rowData.id,
          );
          if (processIndex !== -1) {
            processData[processIndex] = { ...rowData };
            ElMessage.success("工序更新成功");
            // 通知表格组件保存成功
            callback && callback({ success: true });
          } else {
            ElMessage.error("工序更新失败：未找到对应工序");
            // 通知表格组件保存失败
            callback && callback({ success: false });
          }
        }
      } catch (error) {
        console.error("保存工序失败:", error);
        ElMessage.error("保存工序失败: " + (error.message || "未知错误"));
        // 通知表格组件保存失败
        callback && callback({ success: false });
      } finally {
        processLoading.value = false;
      }
    };

    const handleProcessDelete = async (rowData) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除工序 "${rowData.processName}" 吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          },
        );

        processLoading.value = true;
        // 模拟删除工序API调用
        const index = processData.findIndex((item) => item.id === rowData.id);
        if (index !== -1) {
          processData.splice(index, 1);
          ElMessage.success("工序删除成功");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除工序失败:", error);
          ElMessage.error("删除工序失败: " + (error.message || "未知错误"));
        }
      } finally {
        processLoading.value = false;
      }
    };

    // 人员数据相关方法
    const loadPersonnelData = async (params = {}) => {
      try {
        personnelLoading.value = true;
        const searchParams = {
          page: personnelPage.value,
          size: personnelSize.value,
          ...personnelSearchParams.value,
          ...params,
        };

        // 模拟API调用，实际项目中需要替换为真实的API
        const mockResponse = {
          records: personnelData.slice(
            (searchParams.page - 1) * searchParams.size,
            searchParams.page * searchParams.size,
          ),
          total: personnelData.length,
          current: searchParams.page,
          size: searchParams.size,
        };

        personnelTotal.value = mockResponse.total;
        personnelPage.value = mockResponse.current;
        personnelSize.value = mockResponse.size;
      } catch (error) {
        console.error("加载人员数据失败:", error);
        ElMessage.error("加载人员数据失败: " + (error.message || "未知错误"));
      } finally {
        personnelLoading.value = false;
      }
    };

    const handlePersonnelSearch = (searchParams) => {
      personnelSearchParams.value = searchParams;
      personnelPage.value = 1;
      loadPersonnelData();
    };

    const handlePersonnelReset = () => {
      personnelSearchParams.value = {};
      personnelPage.value = 1;
      loadPersonnelData();
    };

    const handlePersonnelPageChange = (params) => {
      personnelPage.value = params.page;
      personnelSize.value = params.size;
      loadPersonnelData();
    };

    const handlePersonnelSizeChange = (params) => {
      personnelPage.value = params.page;
      personnelSize.value = params.size;
      loadPersonnelData();
    };

    const handlePersonnelSave = async (rowData, index, callback) => {
      try {
        personnelLoading.value = true;

        if (rowData.isNew) {
          console.log("新增人员", rowData);
          // 模拟新增人员API调用
          const newPersonnel = {
            ...rowData,
            id: Date.now(), // 模拟ID生成
          };
          personnelData.push(newPersonnel);
          ElMessage.success("人员创建成功");
          // 通知表格组件保存成功
          callback && callback({ success: true });
        } else {
          console.log("更新人员", rowData);
          // 模拟更新人员API调用
          const personnelIndex = personnelData.findIndex(
            (item) => item.id === rowData.id,
          );
          if (personnelIndex !== -1) {
            personnelData[personnelIndex] = { ...rowData };
            ElMessage.success("人员更新成功");
            // 通知表格组件保存成功
            callback && callback({ success: true });
          } else {
            ElMessage.error("人员更新失败：未找到对应人员");
            // 通知表格组件保存失败
            callback && callback({ success: false });
          }
        }
      } catch (error) {
        console.error("保存人员失败:", error);
        ElMessage.error("保存人员失败: " + (error.message || "未知错误"));
        // 通知表格组件保存失败
        callback && callback({ success: false });
      } finally {
        personnelLoading.value = false;
      }
    };

    const handlePersonnelDelete = async (rowData) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除人员 "${rowData.employeeName}" 吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          },
        );

        personnelLoading.value = true;
        // 模拟删除人员API调用
        const index = personnelData.findIndex((item) => item.id === rowData.id);
        if (index !== -1) {
          personnelData.splice(index, 1);
          ElMessage.success("人员删除成功");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除人员失败:", error);
          ElMessage.error("删除人员失败: " + (error.message || "未知错误"));
        }
      } finally {
        personnelLoading.value = false;
      }
    };

    // 切换显示状态
    const toggleProductData = () => {
      showProductData.value = !showProductData.value;
    };

    const toggleEquipmentData = () => {
      showEquipmentData.value = !showEquipmentData.value;
    };

    const toggleProcessData = () => {
      showProcessData.value = !showProcessData.value;
    };

    const togglePersonnelData = () => {
      showPersonnelData.value = !showPersonnelData.value;
    };

    // 获取配置数据
    const getConfigData = () => {
      return {
        productData: [...productData],
        equipmentData: [...equipmentData],
        processData: [...processData],
        personnelData: [...personnelData],
      };
    };

    // 加载配置数据
    const loadConfigData = (data) => {
      if (data.productData) {
        productData.splice(0, productData.length, ...data.productData);
      }
      if (data.equipmentData) {
        equipmentData.splice(0, equipmentData.length, ...data.equipmentData);
      }
      if (data.processData) {
        processData.splice(0, processData.length, ...data.processData);
      }
      if (data.personnelData) {
        personnelData.splice(0, personnelData.length, ...data.personnelData);
      }
    };

    // 验证配置
    const validateConfig = () => {
      const errors = [];

      // 验证产品数据
      if (productData.length === 0) {
        errors.push("至少需要配置一个产品");
      }

      // 验证设备数据
      if (equipmentData.length === 0) {
        errors.push("至少需要配置一台设备");
      }

      // 验证工序数据
      if (processData.length === 0) {
        errors.push("至少需要配置一个工序");
      }

      // 验证人员数据
      if (personnelData.length === 0) {
        errors.push("至少需要配置一名人员");
      }

      return {
        valid: errors.length === 0,
        errors,
      };
    };

    // 重置配置
    const resetConfig = () => {
      // 重置产品数据为空，因为现在从后端加载
      productData.splice(0, productData.length);

      // 重置设备数据为空，因为现在从后端加载
      equipmentData.splice(0, equipmentData.length);

      processData.splice(0, processData.length, {
        id: 1,
        processId: "PR001",
        processName: "原料准备",
        sequence: 1,
        duration: 30,
        skillLevel: "初级",
        equipStatus: "启用",
      });

      personnelData.splice(0, personnelData.length, {
        id: 1,
        employeeId: "EMP001",
        employeeName: "张三",
        department: "生产部",
        position: "机械操作员",
        skillLevel: "高级",
        equipStatus: "在岗",
      });
    };

    // 滚动到指定区块
    const scrollToSection = (section) => {
      const sectionMap = {
        product: productSection,
        equipment: equipmentSection,
        process: processSection,
        personnel: personnelSection,
      };

      const targetSection = sectionMap[section];
      if (targetSection?.value) {
        // 确保对应区块是展开状态
        switch (section) {
          case "product":
            showProductData.value = true;
            break;
          case "equipment":
            showEquipmentData.value = true;
            break;
          case "process":
            showProcessData.value = true;
            break;
          case "personnel":
            showPersonnelData.value = true;
            break;
        }

        // 延迟滚动，等待展开动画完成
        setTimeout(() => {
          targetSection.value.scrollIntoView({
            behavior: "smooth",
            block: "start",
          });
        }, 300);
      }
    };

    // 组件挂载时加载所有数据
    onMounted(() => {
      loadProductData();
      loadEquipmentData();
      loadProcessData();
      loadPersonnelData();
    });

    return {
      // 显示控制
      showProductData,
      showEquipmentData,
      showProcessData,
      showPersonnelData,

      // 表格引用
      productTableRef,
      equipmentTableRef,
      processTableRef,
      personnelTableRef,

      // 区块引用
      productSection,
      equipmentSection,
      processSection,
      personnelSection,

      // 表格列配置
      productColumns,
      equipmentColumns,
      processColumns,
      personnelColumns,

      // 数据
      productData,
      equipmentData,
      processData,
      personnelData,

      // 产品数据相关状态
      productLoading,

      // 设备数据相关状态
      equipmentLoading,

      // 工序数据相关状态
      processLoading,

      // 人员数据相关状态
      personnelLoading,

      // 切换方法
      toggleProductData,
      toggleEquipmentData,
      toggleProcessData,
      togglePersonnelData,

      // 产品数据相关方法
      loadProductData,
      handleProductSearch,
      handleProductReset,
      handleProductSave,
      handleProductDelete,

      // 设备数据相关方法
      loadEquipmentData,
      handleEquipmentSearch,
      handleEquipmentReset,
      handleEquipmentSave,
      handleEquipmentDelete,

      // 工序数据相关方法
      loadProcessData,
      handleProcessSearch,
      handleProcessReset,
      handleProcessSave,
      handleProcessDelete,

      // 人员数据相关方法
      loadPersonnelData,
      handlePersonnelSearch,
      handlePersonnelReset,
      handlePersonnelSave,
      handlePersonnelDelete,

      // 配置方法
      getConfigData,
      loadConfigData,
      validateConfig,
      resetConfig,

      // 滚动方法
      scrollToSection,
    };
  },
};
</script>

<style scoped>
.data-configuration {
  padding: 0;
}

.section-header {
  margin-bottom: 30px;
  text-align: center;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #714b67;
  margin-bottom: 10px;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.section-description {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.aps-section {
  background-color: #ebebeb;
  padding: 15px;
  margin-top: 20px;
  border-radius: 5px;
  scroll-margin-top: 20px;
}

.slide-toggle-enter-active,
.slide-toggle-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.slide-toggle-enter,
.slide-toggle-leave-to {
  max-height: 0;
  opacity: 0;
}

.slide-toggle-enter {
  max-height: 0;
}

.slide-toggle-leave-to {
  max-height: 0;
}

.delete-icon {
  color: #714b67 !important;
}

.delete-icon:hover {
  color: #922575 !important;
}

/* 数据统计样式 */
.statistics-container {
  margin-bottom: 30px;
}

.stat-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.stat-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg,
      var(--card-color-start) 0%,
      var(--card-color-end) 100%);
  transition: height 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.stat-card:hover::before {
  height: 6px;
}

.stat-card:active {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

/* 产品卡片 - 紫红色主题 */
.stat-card-product {
  --card-color-start: #714b67;
  --card-color-end: #922575;
}

.stat-card-product .stat-icon {
  background: linear-gradient(135deg, #714b67 0%, #922575 100%);
}

/* 设备卡片 - 蓝色主题 */
.stat-card-equipment {
  --card-color-start: #017fa5;
  --card-color-end: #0199c9;
}

.stat-card-equipment .stat-icon {
  background: linear-gradient(135deg, #017fa5 0%, #0199c9 100%);
}

/* 工序卡片 - 青色主题 */
.stat-card-process {
  --card-color-start: #16a085;
  --card-color-end: #1abc9c;
}

.stat-card-process .stat-icon {
  background: linear-gradient(135deg, #16a085 0%, #1abc9c 100%);
}

/* 人员卡片 - 橙色主题 */
.stat-card-personnel {
  --card-color-start: #e67e22;
  --card-color-end: #f39c12;
}

.stat-card-personnel .stat-icon {
  background: linear-gradient(135deg, #e67e22 0%, #f39c12 100%);
}

.stat-icon {
  width: 70px;
  height: 70px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  margin-right: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1.2;
  margin-bottom: 6px;
  font-family: "Microsoft YaHei", "Arial", sans-serif;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .stat-card {
    padding: 20px;
  }

  .stat-icon {
    width: 60px;
    height: 60px;
    margin-right: 16px;
  }

  .stat-value {
    font-size: 28px;
  }
}
</style>
